<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>canvas</title>
  <style>
    body {
      text-align: center;
      padding-top: 20px;
    }

    canvas {
      margin: 0 auto;
      box-shadow: 0 0 40px #333;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="800" height="600">
    你的浏览器太low了~
  </canvas>
  <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas')
      if (canvas.getContext) {
        var cvsCtx = canvas.getContext('2d')

        function Rect(x, y, width, height, color, speed) {
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
          this.color = color;
          this.speed = speed;

          this.draw = function () { // 也可以定义成Rect.prototype.draw里
            cvsCtx.beginPath();
            cvsCtx.fillStyle = this.color;
            cvsCtx.fillRect(this.x, this.y, this.width, this.height);
            cvsCtx.closePath();
          }

          this.move = function () {
            this.x += this.speed;

            if (this.x > canvas.width - this.width || this.x < 0) {// 边界判断
              this.speed *= -1;
            }
          }
        }

        var rect1 = new Rect(0, 100, 100, 100, 'red', 2);
        var rect2 = new Rect(700, 100, 100, 100, 'pink', 3);

        function animate() {
          cvsCtx.clearRect(0, 0, canvas.width, canvas.height);
          rect1.move()
          rect2.move()
          rect1.draw();
          rect2.draw();

          // // 检测是否碰撞
          if (isRectHit(rect1, rect2)) {
            rect1.speed *= -1;
            rect2.speed *= -1;
          }

          window.requestAnimationFrame(animate)
        }
        animate()

        // 是否碰撞，这里只针对x轴方向运动
        function isRectHit(rect1, rect2) {
          // 方法1：运动轨迹距离来判断
          // if(rect1.x + rect1.width - rect2.x >= 0) {
          //   return true
          // }
          // 方法2：两个矩形间距
          if (rect2.x - rect1.x <= rect1.width) {
            return true
          }

          return false
        }
      } else {
        alert('你的浏览器太low了~')
      }
    }
  </script>

</body>

</html>